/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AdicaoComponenteMod.java
 *
 * Created on 24/09/2009, 23:45:47
 */

package front.end.subestacao.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Point2D;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import org.jdesktop.application.Action;
import org.jdesktop.swingbinding.JComboBoxBinding;

import front.end.subestacao.exception.TipoFichaException;
import front.end.subestacao.itens.Componente;
import front.end.subestacao.itens.Estado;
import front.end.subestacao.itens.Painel;
import front.end.subestacao.nucleo.ModSubEstFacade;

/**
 * 
 * @author Wilson_2
 */
public class AdicaoComponenteMod extends javax.swing.JDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private ModSubEstFacade modSubEstacao;

	private Componente modeloComponente;
	private Painel painel;
	@SuppressWarnings("unchecked")
	private JComboBoxBinding jComb1;
	@SuppressWarnings("unchecked")
	private JComboBoxBinding jCombEstadoCampo;
	private List<Componente> listaInclusao;
	private Object moldalAnterior;
	private Point2D local;

	public AdicaoComponenteMod(String titulo, ModSubEstFacade modSubEstacao,
			String tipoComponente, Painel painel,
			List<Componente> listaInclusao, JFrame moldalAnteriorFrame, Point2D local) {
 
	 
		super(FrontEndSubApp.getApplication().getMainFrame());
		this.local = local;
	    
		

		this.setTitle(titulo);

		this.modSubEstacao = modSubEstacao;
		this.painel = painel;

		this.modeloComponente = modSubEstacao
				.getModeloComponente(tipoComponente);
		this.listaInclusao = listaInclusao;
		this.moldalAnterior = moldalAnteriorFrame;

		initComponents();
		
		setModal(true);
		
		
		
		List<Estado> estadosCampo = new LinkedList<Estado>();
		estadosCampo.add(new Estado("Aberto", "Campo"));
		estadosCampo.add(new Estado("Fechado", "Campo"));

		this.labelInfo2.setText("do Tipo " + tipoComponente);

		List<Estado> estados = modeloComponente.getPossiveisEstados();

		if (estados.isEmpty()) {
			campoPainelEstado.setVisible(false);
		}
		if (!modeloComponente.getTemEstadoCampo()) {
			campoPainelEstadoCampo.setVisible(false);
		}

		jComb1 = org.jdesktop.swingbinding.SwingBindings
				.createJComboBoxBinding(
						org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ,
						estados, campoEstado);
		jComb1.bind();

		jCombEstadoCampo = org.jdesktop.swingbinding.SwingBindings
				.createJComboBoxBinding(
						org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ,
						estadosCampo, campoEstadoCampo);
		jCombEstadoCampo.bind();
		
		HandlerText handlerText = new HandlerText();  
		campoNome.addActionListener(handlerText);  

	}
	
	 
	   
	
	   
	 private class HandlerText implements ActionListener  
	   {  
	    public void actionPerformed(ActionEvent e)  
	      {  
	    	adicionarComponente();
	      }  
	  }  

	/** Creates new form AdicaoComponenteMod */
	public AdicaoComponenteMod(String titulo, ModSubEstFacade modSubEstacao,
			String tipoComponente, Painel painel,
			List<Componente> listaInclusao, JDialog moldalAnteriorJDialog) {

		super(FrontEndSubApp.getApplication().getMainFrame());
		setModal(true);

		this.setTitle(titulo);

		this.modSubEstacao = modSubEstacao;
		this.painel = painel;

		this.modeloComponente = modSubEstacao
				.getModeloComponente(tipoComponente);
		this.listaInclusao = listaInclusao;
		this.moldalAnterior = moldalAnteriorJDialog;

		initComponents();

		this.labelInfo2.setText("do Tipo " + tipoComponente);

		List<Estado> estados = modeloComponente.getPossiveisEstados();

		if (estados.isEmpty()) {
			campoPainelEstado.setVisible(false);
		}
		if (!modeloComponente.getTemEstadoCampo()) {
			campoPainelEstadoCampo.setVisible(false);
		}

		jComb1 = org.jdesktop.swingbinding.SwingBindings
				.createJComboBoxBinding(
						org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ,
						estados, campoEstado);
		jComb1.bind();

		jCombEstadoCampo = org.jdesktop.swingbinding.SwingBindings
				.createJComboBoxBinding(
						org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ,
						estados, campoEstadoCampo);
		jCombEstadoCampo.bind();
		
		HandlerText handlerText = new HandlerText();  
		campoNome.addActionListener(handlerText);  
	}

	@Action
	public void adicionarComponente() {

		String nome = campoNome.getText();

		if (nome != null) {

			if (nome.equals("") || nome.contains(" ") || nome.contains("-")|| nome.contains("_")) {
				JOptionPane.showMessageDialog(this, "Nome Invalido.", "Erro",
						JOptionPane.ERROR_MESSAGE);
			} else {

				Boolean nomeJaExiste = modSubEstacao.existeCompNome(nome);

				if (nomeJaExiste) {
					JOptionPane.showMessageDialog(this,
							"Ja Existe Um Componente Com Esse Nome.",
							"Erro", JOptionPane.ERROR_MESSAGE);

				} else {

					List<Estado> estadosAtivos = new LinkedList<Estado>();

					if (campoEstado.getSelectedItem() != null) {
						estadosAtivos.add((Estado) campoEstado
								.getSelectedItem());
					}

					Estado estadoCampo = null;
					if (modeloComponente.getTemEstadoCampo()) {
						estadoCampo = (Estado) campoEstadoCampo
								.getSelectedItem();
					}

					Componente compAdicionado = null;
					try {
						compAdicionado = this.modSubEstacao.addComponente(
								painel, modeloComponente.getTipo(), nome,
								estadosAtivos, estadoCampo, local);
					} catch (TipoFichaException e) {

						e.printStackTrace();
					}

					if (this.listaInclusao != null) {

						this.listaInclusao.add(compAdicionado);
						
						if (this.moldalAnterior != null) {
							if (moldalAnterior instanceof AdicaoComponenteDep) {
								AdicaoComponenteDep compDep = (AdicaoComponenteDep) moldalAnterior;
								compDep.atualizaListaEPermissoes(listaInclusao);
							}
							
						}
					} else {
						//System.out.println("inclusao nula");
					}

					this.setVisible(false);

					if (!compAdicionado.getDependencias().isEmpty()) {

						FrontEndSubApp.getApplication().show(
								new AdicaoComponenteDep(
										"Adicao das dependencias do componente "
												+ compAdicionado.toString(),
										modSubEstacao, compAdicionado, painel,
										this, true));
					}

					
					

				}
			}

		}

	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated
	// <editor-fold defaultstate="collapsed" desc="Generated
	// <editor-fold defaultstate="collapsed" desc="Generated
	// <editor-fold defaultstate="collapsed" desc="Generated
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        campoNome = new javax.swing.JTextField();
        campoPainelEstado = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        campoEstado = new javax.swing.JComboBox();
        campoPainelEstadoCampo = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        campoEstadoCampo = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        labelInfo2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(front.end.subestacao.ui.FrontEndSubApp.class).getContext().getResourceMap(AdicaoComponenteMod.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setMinimumSize(new java.awt.Dimension(447, 103));
        setName("Form"); // NOI18N
        setResizable(false);

        jPanel1.setName("jPanel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        campoNome.setText(resourceMap.getString("campoNome.text")); // NOI18N
        campoNome.setName("campoNome"); // NOI18N

        campoPainelEstado.setName("campoPainelEstado"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        campoEstado.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        campoEstado.setName("campoEstado"); // NOI18N

        javax.swing.GroupLayout campoPainelEstadoLayout = new javax.swing.GroupLayout(campoPainelEstado);
        campoPainelEstado.setLayout(campoPainelEstadoLayout);
        campoPainelEstadoLayout.setHorizontalGroup(
            campoPainelEstadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, campoPainelEstadoLayout.createSequentialGroup()
                .addContainerGap(42, Short.MAX_VALUE)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(campoEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 395, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        campoPainelEstadoLayout.setVerticalGroup(
            campoPainelEstadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(campoPainelEstadoLayout.createSequentialGroup()
                .addGroup(campoPainelEstadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        campoPainelEstadoCampo.setName("campoPainelEstadoCampo"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        campoEstadoCampo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        campoEstadoCampo.setName("campoEstadoCampo"); // NOI18N

        javax.swing.GroupLayout campoPainelEstadoCampoLayout = new javax.swing.GroupLayout(campoPainelEstadoCampo);
        campoPainelEstadoCampo.setLayout(campoPainelEstadoCampoLayout);
        campoPainelEstadoCampoLayout.setHorizontalGroup(
            campoPainelEstadoCampoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(campoPainelEstadoCampoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(campoEstadoCampo, 0, 394, Short.MAX_VALUE))
        );
        campoPainelEstadoCampoLayout.setVerticalGroup(
            campoPainelEstadoCampoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(campoPainelEstadoCampoLayout.createSequentialGroup()
                .addGroup(campoPainelEstadoCampoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(campoEstadoCampo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(campoNome, javax.swing.GroupLayout.PREFERRED_SIZE, 394, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(campoPainelEstado, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(campoPainelEstadoCampo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(campoPainelEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(campoPainelEstadoCampo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setIcon(resourceMap.getIcon("jLabel1.icon")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(front.end.subestacao.ui.FrontEndSubApp.class).getContext().getActionMap(AdicaoComponenteMod.class, this);
        jButton1.setAction(actionMap.get("adicionarComponente")); // NOI18N
        jButton1.setIcon(resourceMap.getIcon("jButton1.icon")); // NOI18N
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        labelInfo2.setFont(resourceMap.getFont("labelInfo2.font")); // NOI18N
        labelInfo2.setName("labelInfo2"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelInfo2, javax.swing.GroupLayout.PREFERRED_SIZE, 288, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jButton1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(labelInfo2, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton1ActionPerformed
		// TODO add your handling code here:
	}// GEN-LAST:event_jButton1ActionPerformed

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				// new AdicaoComponenteMod().setVisible(true);
			}
		});
	}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox campoEstado;
    private javax.swing.JComboBox campoEstadoCampo;
    private javax.swing.JTextField campoNome;
    private javax.swing.JPanel campoPainelEstado;
    private javax.swing.JPanel campoPainelEstadoCampo;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel labelInfo2;
    // End of variables declaration//GEN-END:variables

}
